<template>
  <div class="hello">
    <!-- 使用 DynamicScroller 组件实现虚拟滚动，只渲染可视区域的数据 -->
    <DynamicScroller 
      ref="scroller" 
      :items="items" 
      :min-item-size="24" 
      class="scroller" 
      :buffer="800"
      :page-mode="true"
      @resize="scrollToBottom()"
      :prerender="10"
    >
      <template #default="{ item, index, active }">
        <DynamicScrollerItem 
          :item="item" 
          :active="active" 
          :data-index="index"
        >
          <div class="message">
            <img src="../assets/vue.svg" alt="">
            <img src="../assets/vue.svg" alt="">
            <img src="../assets/vue.svg" alt="">
            <img src="../assets/vue.svg" alt="">
            <img src="../assets/vue.svg" alt="">
            <img src="../assets/vue.svg" alt="">
            <img src="../assets/vue.svg" alt="">
            {{ item.text }}
            <img src="../assets/vue.svg" alt="">
            <img src="../assets/vue.svg" alt="">
            <img src="../assets/vue.svg" alt="">
            <img src="../assets/vue.svg" alt="">
            <img src="../assets/vue.svg" alt="">

          </div>
        </DynamicScrollerItem>
      </template>
    </DynamicScroller>
  </div>
</template>

<script>
import { faker } from '@faker-js/faker'

export default {
  name: 'TestChat',

  data() {
    return {
      items: [],
    }
  },

  created() {
    // 分批加载数据以提高性能
    this.loadDataInBatches(99999)
  },

  methods: {
    loadDataInBatches(totalCount, batchSize = 100) {
      let loadedCount = 0
      
      const loadBatch = () => {
        const remaining = totalCount - loadedCount
        const currentBatch = Math.min(batchSize, remaining)
        
        this.addItems(currentBatch)
        loadedCount += currentBatch

        if (loadedCount < totalCount) {
          requestAnimationFrame(loadBatch)
        }
      }

      loadBatch()
    },

    addItems(count = 1) {
      for (let i = 0; i < count; i++) {
        this.items.push({
          text: faker.lorem.lines(),
          id: this.items.length + 1,
        })
      }
      this.scrollToBottom()
    },

    scrollToBottom() {
      console.log('加载完毕')
      this.$nextTick(() => {
        if (this.$refs.scroller) {
          this.$refs.scroller.scrollToBottom()
        }
      })
    },
  },
}
</script>

<style scoped>
.hello {
  flex: 0 1 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.scroller {
  flex: auto 1 1;
  border: 2px solid #ddd;
}

h1,
h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}

.message {
  padding: 10px 10px 9px;
  border-bottom: solid 1px #eee;
}
</style>